package com.nbsaas.boot.controller.lock;

import java.util.concurrent.locks.StampedLock;
import java.util.concurrent.ConcurrentHashMap;

public class StampedLockService implements LockService {

    private final ConcurrentHashMap<String, StampedLock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        StampedLock lock = lockMap.computeIfAbsent(key, k -> new StampedLock());
        long stamp = lock.writeLock();
        return stamp != 0;
    }

    @Override
    public boolean unlock(String key) {
        StampedLock lock = lockMap.get(key);
        if (lock != null) {
            lock.unlockWrite(lock.tryOptimisticRead());
            return true;
        }
        return false;
    }

    @Override
    public boolean isLocked(String key) {
        StampedLock lock = lockMap.get(key);
        return lock != null && lock.isWriteLocked();
    }
}
